package com.abc.controller;

import com.abc.bean.Depart;
import com.abc.service.DepartService;
import com.abc.service.DepartServiceClassFallBack;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 消费者Controller
 */
@RestController
@RequestMapping("/consumer/depart")
public class ConsumerController {
    //注入RestTemplate模板对象
    //@Autowired
    //private RestTemplate restTemplate;

    @Autowired
    private DepartService departService;


    //跨服务新增
    @SentinelResource(fallback = "saveDepart"
            ,fallbackClass = DepartServiceClassFallBack.class)
    @PostMapping("/save")
    public boolean saveHandle(@RequestBody Depart depart) {
        return departService.saveDepart(depart);
    }

    //跨服务根据id查询
    @SentinelResource(value = "getHandle",
            fallback = "getHandlerFallback",
            blockHandler = "getBlockHandlerFallback",
            fallbackClass = DepartServiceClassFallBack.class)
    @GetMapping("/get/{id}")
    public Depart getHandle(@PathVariable("id") int id) {
        return   departService.getDepartById(id);
    }

    public  Depart getBlockHandlerFallback(int id, BlockException e) {
        Depart d= new Depart();
        d.setName("block");
        return d;
    }



    //跨服务根据id删除
    @DeleteMapping("/del/{id}")
    public void deleteHandle(@PathVariable("id") int id) {
        //String url = SERVICE_PROVIDER + "/provider/depart/del/" + id;
        //restTemplate.delete(url);
        departService.removeDepartById(id);
    }
    //跨服务修改
    @PutMapping("/update")
    public void updateHandle(@RequestBody Depart depart) {
        //String url = SERVICE_PROVIDER + "/provider/depart/update";
        //restTemplate.put(url, depart, Boolean.class);
        departService.modifyDepart(depart);
    }

    //跨服务根据列表查询
    @GetMapping("/list")
    public List<Depart> listHandle() {
       // String url = SERVICE_PROVIDER + "/provider/depart/list/";
       // List list = restTemplate.getForObject(url, List.class);
       // return list;
       return departService.listAllDeparts();
    }
}
